package com.biostime.qdingding.modules.qd.web;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.biostime.qdingding.modules.qd.service.CourseService;

/**
 * 临时约课Controller
 * @author king
 * @version 2016-03-09
 */
@Controller
@RequestMapping(value = "${adminPath}/qd/temporder")
public class TempOrderController extends BaseController {
	
	@Autowired
	private ContractService contractService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private CourseOrderService courseOrderService;

	
	@RequiresPermissions("qd:temporder:view")
	@RequestMapping(value = {""})
	public String list(CourseOrder courseOrder, Model model) {
		
		return "modules/qd/tempOrder";
	}
	
	@RequiresPermissions("qd:temporder:add")
	@RequestMapping(value = {"save"})
	public String save(CourseOrder courseOrder,  Model model) {
		//获取需要临时约课的合同
		Contract contract = contractService.get(courseOrder.getContract().getId());
		if(contract == null){
			model.addAttribute("message", "查询不到此合同");
			return list(new CourseOrder(), model);
		}
		courseOrder.setContract(contract);
		//获得需要临时约课的课程
		Course course = courseService.get(courseOrder.getCourse().getId());
		if(course == null){
			model.addAttribute("message", "查询不到此课程");
			return list(new CourseOrder(), model);
		}
		courseOrder.setCourse(course);
		
		CourseOrder order = new CourseOrder();
		order.setCourseId(Integer.valueOf(course.getId()));
		order.setStudentId(Integer.valueOf(contract.getStudent().getId()));
		
		CourseOrder existCourseOrder = courseOrderService.getforcsId(order);
		if(existCourseOrder != null){
			model.addAttribute("message", "该学员在此节课已预约");
		}else{
		courseOrderService.saveTempOrder(courseOrder);
		model.addAttribute("message", "临时约课成功");
		}
		return list(new CourseOrder(), model);
	}

}